<template>
  <div :class="{'inline-block':!block}" class="w-100p" >
    <template>
      <div @click.stop="showPopup"  class="w-100p">
        <slot v-bind:code="val" v-bind:label="labelName"></slot>
      </div>
    </template>
    <van-popup v-model="showPicker" position="bottom" get-container="body">
      <van-picker
        ref="picker"
        :show-toolbar="showToolbar"
        :columns="columns"
        v-bind="$attrs"
        @cancel="cancel"
        @confirm="confirm"
        @change="change"
      />
    </van-popup>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: [String, Array],
      default: ""
    },
    label: {
      type: [String],
      default: ""
    },
    columns: {
      type: Array,
      required: true
    },
    showToolbar: {
      type: Boolean,
      default: true
    },
    visible: {
      type: Boolean,
      default: false
    },
    block: {
      type: Boolean,
      default: true
    },
    readonly: {
      type: Boolean,
      default: false
    },
    deep:{
      type:[String,Number],
      default:0
    },
    dataType:{
      type:String,
      default:''
    }
  },
  mounted() {
  },
  data() {
    return {
      val: this.value,
      valArr: [],
      labelName: "",
      showPicker: this.visible,

    };
  },
  watch: {
    visible(v) {
      this.showPicker = v
    },
    showPicker(v, olv) {
      if (v !== olv) {
        this.$emit('update:visible', v)
      }
    },
    columns: {
      handler(v, oldV) {
        v !== oldV && this.init()
      }
    },
    value: {
      immediate: true,
      handler: function (v, oldV) {
        v !== oldV && this.init()
      }
    }
  },
  computed: {
    attrs() {
      return this.$attrs;
    },
    isMultiple() {
      return this.columns.length && this.columns.some(item => item.children && item.children.length)
    }
  },
  methods: {
    formatValue(v) {
      if (this.isMultiple) {
        return
      } else {
        return v
      }
    },
    init() {
      const v = this.value;
      // let selectVal = '';
      if (v && this.columns.length) {
        let val;//提交的值

        if (this.isMultiple) { //级联
          const len = v.length
          let values = Array.from(Array(len / 2), (empty, i) => {
            return v.slice(0, i * 2 + 2).padEnd(len, 0)
          });
          if(this.dataType==='xzqh' && /(11|12|31|50)\d{4}/.test(v)){
              values.splice(1,1);
          }
          this.deep &&  (values = values.slice(0,this.deep));
          // 
          const { labelName, val, valArr } = this.findItem(values, 'code', (column, i) => {
            this.$set(column,"defaultIndex",i);
          });
          this.labelName = labelName;// 级联默认去最后一个值，名称
          this.val = val
          this.valArr = valArr
          // selectVal = valArr

          // selectVal && this.$refs.picker && this.$refs.picker.setValues && this.$refs.picker.setValues(selectVal)
        } else if (typeof v === 'string' && v.length) {//单选
          val = v;
          const labelName = this.columns.find((item, i) => {
            const { code } = item
            const flag = code === v
            flag && this.$set(item,"defaultIndex",i);
            return flag
          }).text || "";
          this.labelName = labelName
          // selectVal = val
          this.val = val;

          // selectVal && this.$refs.picker && this.$refs.picker.setValues && this.$refs.picker.setValues([selectVal])
        }
        this.$emit('update:label', this.labelName)
        // selectVal && this.$refs.picker && this.$refs.picker.setValues && this.$refs.picker.setValues(selectVal)
      }
    },
    showPopup() {
      if (!this.readonly) {
        this.showPicker = true;
      }
    },
    change() {
      this.$emit("change", ...arguments);
    },
    findItem(values = [], key, cb = () => { }) {

      let { columns } = this;
      let labelName = '',
        val = '',
        valArr = [];

      let lvl = 0;

      const fn = (arr) => {
        arr.forEach((column, i) => {
          if (column[key] === values[lvl]) {
            lvl++;
            val = column.code;
            labelName = column.text;
            valArr.push(column.code);
            cb && cb(column, i)
            column.children && fn(column.children)
          }
        });

      };



      if (values.length !== 0) {
        fn(columns)
      }


      return {
        labelName,
        val,
        valArr
      }
    },
    confirm(value) {
      let info=null;
      if (Array.isArray(value)) { // ['1100','1101']
      info=[]
        const { labelName, val, valArr } = this.findItem(value, 'text',(column)=>{
          info.push(column)
        });
        this.labelName = labelName;// 级联默认去最后一个值，名称
        this.val = val
        this.valArr = valArr

      } else {
        this.val = value.code;
        info=value
      }

      this.showPicker = false;

      this.$emit("input", this.val);
      this.$emit("confirm", value,info);
    },
    cancel() {
      this.showPicker = false;
      this.$emit("cancel");
    }
  }
};
</script>

<style lang="less" scoped>
.inline-block {
  display: inline-block;
}
.date-blue {
  color: #3b3b4c;
  span {
    margin: 0 6px;
    padding: 2px 6px;
    background: #025eb3;
    color: #fff;
    border-radius: @radius-4;
  }
}
.padding0 {
  padding: 0;
}
.picker.van-cell:not(:last-child)::after {
  display: none;
}
</style>